import 'dart:io';
import 'package:camera/camera.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class CameraService {
  static final CameraService _instance = CameraService._internal();
  factory CameraService() => _instance;
  CameraService._internal();

  final ImagePicker _imagePicker = ImagePicker();
  CameraController? _cameraController;
  List<CameraDescription>? _cameras;

  // 初始化相机
  Future<bool> initializeCamera() async {
    try {
      // 检查相机权限
      final cameraPermission = await Permission.camera.request();
      if (cameraPermission != PermissionStatus.granted) {
        return false;
      }

      // 获取可用相机列表
      _cameras = await availableCameras();
      if (_cameras == null || _cameras!.isEmpty) {
        return false;
      }

      // 初始化相机控制器
      _cameraController = CameraController(
        _cameras!.first,
        ResolutionPreset.high,
        enableAudio: false,
      );

      await _cameraController!.initialize();
      return true;
    } catch (e) {
      print('相机初始化错误: $e');
      return false;
    }
  }

  // 获取相机控制器
  CameraController? get cameraController => _cameraController;

  // 获取可用相机列表
  List<CameraDescription>? get cameras => _cameras;

  // 切换前后摄像头
  Future<bool> switchCamera() async {
    if (_cameras == null || _cameras!.length < 2) {
      return false;
    }

    try {
      final currentCamera = _cameraController!.description;
      final newCamera = _cameras!.firstWhere(
        (camera) => camera.lensDirection != currentCamera.lensDirection,
        orElse: () => _cameras!.first,
      );

      await _cameraController!.dispose();
      _cameraController = CameraController(
        newCamera,
        ResolutionPreset.high,
        enableAudio: false,
      );

      await _cameraController!.initialize();
      return true;
    } catch (e) {
      print('切换相机错误: $e');
      return false;
    }
  }

  // 拍照
  Future<String?> takePicture() async {
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      return null;
    }

    try {
      final XFile image = await _cameraController!.takePicture();
      
      // 将图片保存到应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String fileName = 'business_card_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(appDocDir.path, fileName);
      
      final File imageFile = File(image.path);
      await imageFile.copy(filePath);
      
      return filePath;
    } catch (e) {
      print('拍照错误: $e');
      return null;
    }
  }

  // 从相册选择图片
  Future<String?> pickImageFromGallery() async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );

      if (image == null) return null;

      // 将图片保存到应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String fileName = 'business_card_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(appDocDir.path, fileName);
      
      final File imageFile = File(image.path);
      await imageFile.copy(filePath);
      
      return filePath;
    } catch (e) {
      print('选择图片错误: $e');
      return null;
    }
  }

  // 从相机拍照
  Future<String?> pickImageFromCamera() async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );

      if (image == null) return null;

      // 将图片保存到应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String fileName = 'business_card_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(appDocDir.path, fileName);
      
      final File imageFile = File(image.path);
      await imageFile.copy(filePath);
      
      return filePath;
    } catch (e) {
      print('相机拍照错误: $e');
      return null;
    }
  }

  // 检查相机权限
  Future<bool> checkCameraPermission() async {
    final status = await Permission.camera.status;
    return status == PermissionStatus.granted;
  }

  // 请求相机权限
  Future<bool> requestCameraPermission() async {
    final status = await Permission.camera.request();
    return status == PermissionStatus.granted;
  }

  // 检查相册权限
  Future<bool> checkGalleryPermission() async {
    final status = await Permission.photos.status;
    return status == PermissionStatus.granted;
  }

  // 请求相册权限
  Future<bool> requestGalleryPermission() async {
    final status = await Permission.photos.request();
    return status == PermissionStatus.granted;
  }

  // 释放相机资源
  Future<void> dispose() async {
    await _cameraController?.dispose();
    _cameraController = null;
  }
}
